﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Zx
{
    public static class EnumerableExt
    {
        public static IList<T> Convert<fT, T>(this IEnumerable<fT> items, Func<fT, T> func)
        {
            var ret = new List<T>();
            try
            {
                items.ForEach(i => ret.Add(func(i)));
                return ret;
            }
            catch (Exception)
            {

                throw;
            }
        }

        public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
        {
            try
            {
                foreach (T item in items)
                {
                    action(item);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        public static bool Contains<T, T2>(this IEnumerable<T> items, T2 value, Func<T, T2> func)
        {
            if (func == null)
                return false;
            if (value == null)
                return false;
            if (items == null)
                return false;
            foreach (var t in items)
            {
                if (func(t).Equals(value))
                    return true;
            }
            return false;
        }

        public static T GetItemWithTheValue<T, T2>(this IEnumerable<T> items, T2 value, Func<T, T2> func) where T : class
        {
            if (func == null)
                return null;
            if (value == null)
                return null;
            if (items == null)
                return null;
            foreach (var t in items)
            {
                if (func(t).Equals(value))
                    return t;
            }
            return null;
        }
        public static void EachDo<T>(this IEnumerable<T> items, Action<T> action)
        {
            if(items==null||items.Count()==0)
            {
                return;
            }
            items.ToList().ForEach(action);
        }
    }
}
